package com.mibsvc.appsvc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.Base64;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by litarchain on 2017/5/24.
 */
public class InCodeUtils {

    public static Mjson decode(String in) {
        String out = "";
        String s[] = in.split("&");
        String body = "";
        String serviceName="";
        String activeId = "";
        for(int i=0;i<s.length;i++){
            if ("param".equals(s[i].split("=")[0])) {
                try {
                    body = new String(Base64.decodeFast(s[i].substring(6).replaceAll("%3D", "=").replaceAll("%2B", "+").replaceAll("%2F", "/")), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if ("serviceName".equals(s[i].split("=")[0])) {
                serviceName = s[i].substring(12);
            } else if ("activeId".equals(s[i].split("=")[0])) {
                activeId = s[i].substring("activeId".length() + 1);
            }


        }

        System.out.println("Utilbody==" + body);

        Mjson m = new Mjson();
        Map tmpRoot = (Map) JSON.parseObject(body, LinkedHashMap.class);
        m.setRoot("ROOT.BODY", tmpRoot);


        System.out.println("tmpRoot==" + tmpRoot);
        //m.setRoot("ROOT.BODY",tmpRoot);
        m.setBody(tmpRoot);
        m.setRoot("ROOT.HEADER.SERVICE.SERVICE_NAME", serviceName);
        m.setRoot("ROOT.HEADER.ACTIVE.ACTIVE_ID", activeId);
        return m;
    }

    public static String getBase64(String str) {

        try {
            return (new BASE64Encoder()).encodeBuffer(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

    }
}